package com.saikuo.service.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.saikuo.service.constant.Config;
import com.saikuo.service.constant.ContextConfig;
import com.saikuo.service.dao.IAdvertisementDao;
import com.saikuo.service.service.IAdvertisementService;
import com.saikuo.service.utils.JSONUtil;
import com.saikuo.service.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by chenzhuo on 16/7/25.
 */
@Service
public class AdvertisementServiceImpl implements IAdvertisementService {

    @Autowired
    private Config config;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private IAdvertisementDao advertisementDao;

    @Override
    public PicturePreView getPicUrlPre() {
        PicturePreView picturePreView = new PicturePreView();
        picturePreView.setPicUrlPre(config.getPicUrl());
        return picturePreView;
    }

    @Override
    public List<BannerView> getBanner() {
        return advertisementDao.getBanner();
    }

    @Override
    public List<CategoryView> getCategory() {
        List<CategoryView> categoryViews = new ArrayList<>();
        // 设置缓存KEY
        String key = getKeyParameterById("getCategory", null);
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        String value = valueOperations.get(key);
        // 若缓存中存在，则直接返回
        if (!StringUtils.isEmpty(value)) {
            JSONArray array = JSONArray.parseArray(value);
            for (int i = 0; i < array.size(); i++) {
                String jsonObject = array.getJSONObject(i).toJSONString();
                CategoryView categoryView = JSONUtil.jsonToBeanWithJackson(jsonObject,
                        CategoryView.class);
                categoryViews.add(categoryView);
            }
            return categoryViews;
        }
        // 若缓存中不存在，则查DB
        categoryViews = advertisementDao.getCategory();
        if (categoryViews != null) {
            valueOperations.set(key, JSONUtil.beanToJsonWithJackson(categoryViews),
                    ContextConfig.DAYS_7, TimeUnit.DAYS);
        }
        return categoryViews;
    }

    @Override
    public List<TopicSaleView> getTopicSale() {
        return advertisementDao.getTopicSale();
    }

    @Override
    public PostageView getPostageView() {
        return advertisementDao.getPostageView();
    }

    private static String getKeyParameterById(String funName, Object param) {
        return getCacheClassPrefix() + funName + "_" + param;
    }

    private static String getCacheClassPrefix() {
        return AdvertisementServiceImpl.class.getName() + "_";
    }

}
